#include <Reg51.h>
#include "LCD1602.h"
#include "delay.h"
#include "ds1302.h"

unsigned char timerFlag = 0;
unsigned char backupsec = 0xAA;

void LCDDisplay();
void Timer0Init(void);


void main()
{
	LCDInit();
	//DS1302Init();//初始化 初始时间：DATE:2020-09-14 
	Timer0Init();						//  TIME:08：00：00  星期
	DS1302BurstInit();
	DelayXms(20);
	while(1)
	{
		if (timerFlag)
		{
			timerFlag = 0;
			DS1302BurstRead(time);
			if (backupsec != time[0])
			{
				LCDDisplay();
				backupsec = time[0];
			}
		}
		//DS1302ReadTimer();
		
		
	}
}

void LCDDisplay()
{
	unsigned char str[16];
	str[0] = 'D';
	str[1] = 'A';
	str[2] = 'T';
	str[3] = 'E';
	str[4] = ':';
	str[5] = '2';
	str[6] = '0';
	str[7] = (time[6] >> 4) + '0';//年
	str[8] = (time[6] & 0x0f) + '0';
	str[9] = '-';
	str[10] = (time[4] >> 4) + '0';//月
	str[11] = (time[4] & 0x0f) + '0';
	str[12] = '-';
	str[13] = (time[3] >> 4) + '0';//日
	str[14] = (time[3] & 0x0f) + '0';
	str[15] = '\0';
	LCDShowStr(0,0,str);
	
	str[0] = 'T';
	str[1] = 'I';
	str[2] = 'M';
	str[3] = 'E';
	str[4] = ':';
	str[5] = (time[2] >> 4) + '0';//时
	str[6] = (time[2] & 0x0f) + '0';
	str[7] = ':';
	str[8] = (time[1] >> 4) + '0';//分
	str[9] = (time[1] & 0x0f) + '0';
	str[10] = ':';
	str[11] = ((time[0]&0x7F) >> 4) + '0';//秒
	str[12] = (time[0] & 0x0f) + '0';
	str[13] = ' ';
	str[14] = ((time[5] - 1) & 0x0f) + '0';
	str[15] = '\0';
	LCDShowStr(0,1,str);
}

void Timer0Init(void)		//1毫秒@11.0592MHz
{
	TMOD &= 0xF0;		//设置定时器模式
	TMOD |= 0x01;		//设置定时器模式
	TL0 = 0x66;		//设置定时初值
	TH0 = 0xFC;		//设置定时初值
	TF0 = 0;		//清除TF0标志
	ET0 = 1;
	EA = 1;
	TR0 = 1;		//定时器0开始计时
}

void timer0_ISR() interrupt 1
{
	static unsigned char timer0Cnt = 0;
	TR0 = 0;
	timer0Cnt++;
	if (timer0Cnt >= 200)
	{
		timer0Cnt = 0;
		timerFlag = 1;
	}
	TL0 = 0x66;		//设置定时初值
	TH0 = 0xFC;		//设置定时初值
	TR0 = 1;
}